var app = getApp()
const time = require('../../utils/time.js')
const util = require('../../utils/util.js')
const socketOpen = false
const socketMsgQueue = []
const requireHttps = app.globalData.requireHttps //获取require域名
Page({

  data: {
    items: [],
    startX: 0, //开始坐标
    startY: 0,
    data_active: 1,
    showView: true,
    orderList: [],
    car_Id: '',
    gp_name: '',
    gp_price: '',
    o_license: '',
    o_money: '',
    when: '',
    payType: 1,
    noOrder: '',
    showOrder: true,
    itemsTime: [],
    nowTime: '',
    interval: '',
    name: '',
    address: ''
  },
  onLoad: function() {
    let _this = this
    _this.getUserOrder();

  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function(e) {
    //开始触摸时 重置所有删除
    this.data.items.forEach(function(v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      items: this.data.items
    })
  },

  //滑动事件处理
  touchmove: function(e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.items.forEach(function(v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })

    //更新数据
    that.setData({
      items: that.data.items
    })
  },

  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function(start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  //删除事件
  del: function(e) {
    let _this = this
    console.log(e.currentTarget.dataset.o_id)
    wx.request({
      url: '' + requireHttps + '/Api/Order/delOrder',
      data: {
        o_id: e.currentTarget.dataset.o_id
      },
      method: 'post',
      success: res => {
        console.log(res)
        wx.showToast({
          title: '删除成功',
        })
        _this.data.items.splice(e.currentTarget.dataset.index, 1)
        _this.setData({
          items: _this.data.items
        })
      }
    })
  },

  //切换支付方式
  payTab: function(e) {
    let _this = this;
    // console.log(e)
    _this.data.payType = e.currentTarget.dataset.active
    _this.setData({
      data_active: e.currentTarget.dataset.active
    })
  },
  openPay: function(e) {
    let _this = this;
    let when = e.currentTarget.dataset.when
    let o_money = e.currentTarget.dataset.o_money
    _this.setData({
      when: e.currentTarget.dataset.when,
      o_money: e.currentTarget.dataset.o_money
    })
    // _this.getUserOrder()
    // wx.hideLoading()
    clearInterval(_this.data.interval)
    _this.setData({
      showView: (!_this.data.showView),
      gp_name: e.currentTarget.dataset.gp_name,
      gp_price: e.currentTarget.dataset.gp_price,
      o_license: e.currentTarget.dataset.o_license,
      o_id: e.currentTarget.dataset.o_id
    })
    
  },
  //显示隐藏支付费用
  closePay: function(e) {
    // console.log(e)
    let _this = this
    // _this.getUserOrder()
    // wx.hideLoading()
    _this.setData({
      showView: (!_this.data.showView)
    })
  },
  nowTime(t) {
    console.log(t)
    t++;
    setTimeout(() => {
      this.nowTime(t)
    }, 1000)
    return app.sec2time(parseInt(t / 1000))
  },
  
  //获取用户订单
  getUserOrder: function() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let _this = this
    //发起网络请求获取用户订单列表
    wx.request({
      url: '' + requireHttps + '/api/order/getUserOrderList',
      data: {
        token: app.globalData.token,
        page: 1,
        lng: app.globalData.longitude,
        lat: app.globalData.latitude
      },
      method: 'post',
      success: res => {
        let data = res.data.data
        // console.log(res.data.data)
        _this.setData({
          items: res.data.data
        })
        if (data == '') {
          _this.setData({
            noOrder: '暂无订单',
            showOrder: false
          })
        }

        //虚拟计时用户订单时间
        _this.data.interval = setInterval(() => {
          _this.data.itemsTime = []
          for (let i = 0; i < data.length; i++) {
            //当前时间
            let date = new Date()
            let startDate = new Date(data[i].o_start_time)
            let timeLag = (date / 1000 - startDate)
            let nowTimeLag = app.timeLag(timeLag)
            _this.data.itemsTime.push({
              o_status: data[i].o_status,
              isTime: nowTimeLag,
            })
            if (data[i].o_status == 1) {
              _this.setData({
                isTime: nowTimeLag
              })
            }
            //判断是否push完成
            if (data.length == _this.data.itemsTime.length) {
              _this.setData({
                itemsTime: _this.data.itemsTime
              })
            }
          }
        }, 1000)
        // clearInterval(_this.data.interval)
        setTimeout(() => {
          wx.hideLoading()
        },1000)
      }
    })
  },
  //用户点击确认支付
  surePay: util.throttle(function(e) {
    let _this = this
    //发起网络请求生成微信支付订单
    wx.request({
      url: '' + requireHttps + '/api/pay/createPayOrder',
      data: {
        openid: app.globalData.openid,
        o_id: e.currentTarget.dataset.id,
        token: app.globalData.token,
        type: _this.data.payType
      },
      method: 'post',
      success: res => { //请求成功
        console.log(res)
        if (_this.data.payType == 1) {
          console.log('余额支付')
          wx.showModal({
            title: '提示',
            content: res.data.message,
            success: res => {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              } else if (res.cancel) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
          return false
        }
        //存储用户支付参数
        let timeStamp = res.data.data.timeStamp
        let nonceStr = res.data.data.nonceStr
        let packages = res.data.data.package
        let signType = res.data.data.signType
        let paySign = res.data.data.paySign

        //发起微信支付
        wx.requestPayment({
          timeStamp: timeStamp,
          nonceStr: nonceStr,
          package: packages,
          signType: signType,
          paySign: paySign,
          success: res => {
            console.log('微信支付')
            wx.showToast({
              title: res.data.message,
              success: res => {
                //支付成功跳转个人中心
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                } else if (res.cancel) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }
        })
      }
    })
  },1000),
  //再次预定
  againReserve: function(e) {
    wx.navigateTo({
      url: '/pages/parking/parking',
    })
  },
  goParking: function(e) {
    let _this = this
    console.log(e)
    // console.log('1111')
    // let latitude = parseFloat(_this.data.latitude)
    // let longitude = parseFloat(_this.data.longitude)
    // console.log(latitude)
    wx.openLocation({
      latitude: parseFloat(e.currentTarget.dataset.latitude),
      longitude: parseFloat(e.currentTarget.dataset.longitude),
      scale: 18,
      name: e.currentTarget.dataset.name,
      address: e.currentTarget.dataset.address
    })
  }
})